from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from .models import VideoTask
from .utils import VolcVideoAPI
import json
import logging

logger = logging.getLogger(__name__)


def video_list(request):
    """AI视频制作列表"""
    tasks = VideoTask.objects.filter(is_deleted=False).order_by('-create_time')
    return render(request, 'ai_video/video_list.html', {
        'tasks': tasks
    })


def create_video(request):
    """AI视频制作表单"""
    if request.method == 'POST':
        prompt = request.POST.get('prompt')
        resolution = request.POST.get('resolution', '480p')  # 默认480p
        aspect_ratio = request.POST.get('aspect_ratio', '21:9')  # 默认21:9
        duration = int(request.POST.get('duration', 5))  # 默认5秒
        
        if prompt:
            if request.user.is_authenticated:
                user = request.user
            else:
                from django.contrib.auth.models import User
                user, created = User.objects.get_or_create(username='anonymous')
            
            # 调用火山API创建任务
            try:
                from .utils import VolcVideoAPI
                api = VolcVideoAPI()
                task = api.create_task(
                    user=user,
                    prompt=prompt,
                    resolution=resolution,
                    aspect_ratio=aspect_ratio,
                    duration=duration
                )
                messages.success(request, '视频制作任务已创建！')
                return redirect('ai_video:video_list')
            except Exception as e:
                messages.error(request, f'创建任务失败：{str(e)}')
        else:
            messages.error(request, '请填写提示词')
    
    return render(request, 'ai_video/create_video.html')


# =========================== API接口 ===========================

# @login_required  # 临时注释掉用于测试
@csrf_exempt     # 测试用，生产环境要去掉并配置CSRF
@require_http_methods(["POST"])
def create_video_task(request):
    """
    创建视频任务接口
    请求参数：
    - prompt: 文字提示词（必需，包含--参数）
    """
    try:
        # 获取请求参数
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            prompt = data.get('prompt', '').strip()
            resolution = data.get('resolution', '480p')  # 默认480p
            aspect_ratio = data.get('aspect_ratio', '21:9')  # 默认21:9
            duration = data.get('duration', 5)  # 默认5秒
        else:
            # form-data格式
            prompt = request.POST.get('prompt', '').strip()
            resolution = request.POST.get('resolution', '480p')  # 默认480p
            aspect_ratio = request.POST.get('aspect_ratio', '21:9')  # 默认21:9
            duration = int(request.POST.get('duration', 5))  # 默认5秒
        
        # 参数校验
        if not prompt:
            return JsonResponse({"code": 400, "msg": "请输入文字提示词"})
        
        # 验证分辨率
        valid_resolutions = ['480p', '720p', '1080p']
        if resolution not in valid_resolutions:
            return JsonResponse({"code": 400, "msg": f"分辨率必须是{valid_resolutions}之一"})
        
        # 验证宽高比
        valid_aspect_ratios = ['16:9', '9:16', '1:1', '4:3', '21:9']  # 添加21:9
        if aspect_ratio not in valid_aspect_ratios:
            return JsonResponse({"code": 400, "msg": f"宽高比必须是{valid_aspect_ratios}之一"})
        
        # 验证时长
        valid_durations = [3, 5, 6, 9, 10, 12]  # 添加5和10秒
        if duration not in valid_durations:
            return JsonResponse({"code": 400, "msg": f"时长必须是{valid_durations}之一"})
        
        # 提示词长度校验
        if len(prompt) > 200:
            return JsonResponse({"code": 400, "msg": "提示词不能超过200字"})
        
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        # 调用火山API创建任务
        api = VolcVideoAPI()
        task = api.create_task(
            user=user, 
            prompt=prompt,
            resolution=resolution,
            aspect_ratio=aspect_ratio,
            duration=duration
        )
        
        return JsonResponse({
            "code": 200,
            "msg": "任务创建成功",
            "data": {
                "task_id": task.volc_task_id,
                "status": task.status,
                "prompt": task.prompt,
                "resolution": task.resolution,
                "aspect_ratio": task.aspect_ratio,
                "duration": task.duration,
                "price": float(task.price),  # 添加价格字段
                "create_time": task.create_time.strftime('%Y-%m-%d %H:%M:%S')
            }
        })
        
    except Exception as e:
        return JsonResponse({"code": 500, "msg": str(e)})


# @login_required  # 临时注释掉用于测试
@csrf_exempt
@require_http_methods(["POST"])
def query_video_task(request):
    """
    查询任务进度接口
    请求参数：
    - volc_task_id: 火山任务ID（必需）
    """
    try:
        # 获取请求参数
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            volc_task_id = data.get('volc_task_id', '').strip()
        else:
            volc_task_id = request.POST.get('volc_task_id', '').strip()
        
        if not volc_task_id:
            return JsonResponse({"code": 400, "msg": "请传入火山任务ID"})
        
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        # 获取任务
        api = VolcVideoAPI()
        task = api.get_task_by_id(user, volc_task_id)
        
        # 查询最新状态
        updated_task = api.query_task(task)
        
        return JsonResponse({
            "code": 200,
            "msg": "查询成功",
            "data": {
                "task_id": updated_task.volc_task_id,
                "status": updated_task.status,
                "video_url": updated_task.video_url,  # 成功的话会有链接
                "error_msg": updated_task.error_msg,   # 失败的话会有原因
                "prompt": updated_task.prompt,
                "resolution": updated_task.resolution,
                "aspect_ratio": updated_task.aspect_ratio,
                "duration": updated_task.duration,
                "price": float(updated_task.price),  # 添加价格字段
                "create_time": updated_task.create_time.strftime('%Y-%m-%d %H:%M:%S')
            }
        })
        
    except Exception as e:
        return JsonResponse({"code": 500, "msg": str(e)})


# @login_required  # 临时注释掉用于测试
@csrf_exempt
@require_http_methods(["GET"])
def list_video_tasks(request):
    """
    获取用户的所有视频任务列表
    参数：
    - page: 页码（默认1）
    - page_size: 每页数量（默认10）
    - status: 状态过滤（可选）
    """
    try:
        # 获取参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        status_filter = request.GET.get('status', '').strip()
        
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        # 查询用户的任务
        tasks = VideoTask.objects.filter(
            user=user,
            is_deleted=False
        ).order_by('-create_time')
        
        # 状态过滤
        if status_filter:
            tasks = tasks.filter(status=status_filter)
        
        # 分页
        total = tasks.count()
        start = (page - 1) * page_size
        end = start + page_size
        task_list = tasks[start:end]
        
        # 组装返回数据
        data = []
        for task in task_list:
            data.append({
                "task_id": task.volc_task_id,
                "status": task.status,
                "video_url": task.video_url,
                "error_msg": task.error_msg,
                "prompt": task.prompt,
                "resolution": task.resolution,
                "aspect_ratio": task.aspect_ratio,
                "duration": task.duration,
                "price": float(task.price),  # 添加价格字段
                "create_time": task.create_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            "code": 200,
            "msg": "查询成功",
            "data": {
                "tasks": data,
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size
            }
        })
        
    except Exception as e:
        return JsonResponse({"code": 500, "msg": str(e)})





# @login_required  # 临时注释掉用于测试
@csrf_exempt
@require_http_methods(["POST"])
def delete_video_task(request):
    """
    软删除视频任务
    请求参数：
    - volc_task_id: 火山任务ID（必需）
    """
    try:
        # 获取请求参数
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            volc_task_id = data.get('volc_task_id', '').strip()
        else:
            volc_task_id = request.POST.get('volc_task_id', '').strip()
        
        if not volc_task_id:
            return JsonResponse({"code": 400, "msg": "请传入火山任务ID"})
        
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        # 获取任务（只能删除自己的）
        api = VolcVideoAPI()
        task = api.get_task_by_id(user, volc_task_id)
        
        # 软删除
        task.is_deleted = True
        task.save()
        
        return JsonResponse({
            "code": 200,
            "msg": "删除成功"
        })
        
    except Exception as e:
        return JsonResponse({"code": 500, "msg": str(e)})
